package com.yq.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yq.reggie.dto.DishDto;
import com.yq.reggie.pojo.Dish;
import com.yq.reggie.pojo.DishFlavor;
import com.yq.reggie.service.CategoryService;
import com.yq.reggie.service.DishFlavorService;
import com.yq.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value="dishCache",key="#dishDto.categoryId")
    public Result add(@RequestBody DishDto dishDto){
        return dishService.addWithDishFlavor(dishDto);
    }

    /**
     * 分页展示
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result selectPage(Integer page,Integer pageSize,String name){
        //创建分页对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        //创建条件构造器对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //分页查询
        dishService.page(pageInfo,queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<DishDto> dishDtos =new ArrayList<>();
        List<Dish> records = pageInfo.getRecords();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            dishDto.setCategoryName(categoryService.getById(record.getCategoryId()).getName());
            dishDtos.add(dishDto);
        }
         dishDtoPage.setRecords(dishDtos);
      /*  List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setCategoryName(categoryService.getById(item.getCategoryId()).getName());
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);*/
        return Result.success(dishDtoPage);
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value="dishCache",allEntries = true)
    public Result delete(Long[] ids){
        return dishService.deleteWithDishFlavor(ids);
    }

    /**
     * 修改菜品 ：页面回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @CacheEvict(value="dishCache",allEntries = true)
    public Result modify_display(@PathVariable Long id){

        return dishService.modify_displayWithDisFlavor(id);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result modify(@RequestBody DishDto dishDto){
        return dishService.modifyWithDishFlavor(dishDto);
    }

    /**
     * 修改菜品状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result status(@PathVariable Integer status,Long[] ids){
        Dish dish = new Dish();
        for (Long id : ids) {
            //根据id修改菜品状态
            dish.setStatus(status);
            dish.setId(id);
            dishService.updateById(dish);
        }
        return Result.success("修改菜品状态成功");
    }

    /**
     * 添加套餐页面回显（添加菜品）：根据分类id查询菜品名称
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value="dishCache",key = "#dish.categoryId")
    public Result selectNameByCategoryId(Dish dish){
        //创建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询菜品
        List<Dish> dishes = dishService.list(queryWrapper);
        //对象拷贝
        List<DishDto> list = dishes.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            LambdaQueryWrapper<DishFlavor> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(DishFlavor::getDishId, item.getId());
            BeanUtils.copyProperties(item,dishDto);
            dishDto.setFlavors(dishFlavorService.list(queryWrapper2));
            return dishDto;
        }).collect(Collectors.toList());

        return Result.success(list);
    }
}
